import React, { useState, useEffect } from 'react';
import axios from 'axios';
import html2canvas from 'html2canvas';
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
import MatchListTab from './MatchListTab';
import './App.css';

function App() {
  const [matches, setMatches] = useState([]);
  const [selectedMatches, setSelectedMatches] = useState([]);
  const [combinations, setCombinations] = useState([]);
  const [dataUrl, setDataUrl] = useState("https://webapi.sporttery.cn/gateway/lottery/getFootBallMatchV1.qry?param=90,0&lotteryDrawNum=&sellStatus=0&termLimits=10");
  const [drawNum, setDrawNum] = useState(""); // 手动输入的期号
  const [drawNums, setDrawNums] = useState([]); // 期号列表
  const [selectedDrawNum, setSelectedDrawNum] = useState(""); // 下拉选择的期号
  const [useManualDrawNum, setUseManualDrawNum] = useState(false); // 是否使用手动输入
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('main'); // 'main' | 'matchList'
  const [stats, setStats] = useState({
    selectedCount: 0,
    comboCount: 0,
    totalBets: 0
  });
  const [resultStats, setResultStats] = useState({
    totalCombinations: 0,
    totalBets: 0,
    totalAmount: 0
  });

  // 初始化加载数据
  useEffect(() => {
    fetchMatches();
  }, []);

  // 获取比赛数据 - 支持期号查询
  const fetchMatches = async () => {
    try {
      setLoading(true);
      // 先获取期号列表
      const drawResponse = await axios.get('/api/lottery/draws');
      setDrawNums(drawResponse.data);
      // 确定使用的期号
      const currentDrawNum = useManualDrawNum ? drawNum : selectedDrawNum;
      // 构建请求URL
      let requestUrl = dataUrl;
      if (drawNum) {
        requestUrl = `https://webapi.sporttery.cn/gateway/lottery/getFootBallMatchV1.qry?param=90,0&lotteryDrawNum=${currentDrawNum}&sellStatus=1&termLimits=10`;
      }

      const response = await axios.get('/api/lottery/matches', {
        params: {
          url: requestUrl,
          drawNum: currentDrawNum // 传递期号给后端
        }
      });
      setMatches(response.data);

      // 初始化选择状态
      const initialSelections = response.data.map(match => ({
        matchId: match.id,
        select3: false,
        select1: false,
        select0: false
      }));
      setSelectedMatches(initialSelections);
      updateStats(initialSelections);
    } catch (error) {
      console.error('获取比赛数据失败:', error);
    } finally {
      setLoading(false);
    }
  };
// 新增：随机选择指定数量的比赛并生成组合
  const randomSelectAndGenerate = (count) => {
    if (count < 9 || count > 14) {
      alert("请选择9-14之间的数字");
      return;
    }
    // 检查是否有足够的比赛
    if (matches.length < count) {
      alert(`当前只有${matches.length}场比赛，无法选择${count}场`);
      return;
    }
    // 随机选择指定数量的比赛
    const shuffled = [...matches].sort(() => 0.5 - Math.random());
    const selected = shuffled.slice(0, count);

    // 为每场比赛随机选择1-2个结果
    const randomSelections = matches.map(match => {
      const isSelected = selected.some(m => m.id === match.id);
      if (!isSelected) {
        return { matchId: match.id, select3: false, select1: false, select0: false };
      }

      // 随机选择1-2个结果
      const choices = [];
      const numChoices = Math.floor(Math.random() * 2) + 1;
      while (choices.length < numChoices) {
        const choice = ['select3', 'select1', 'select0'][Math.floor(Math.random() * 3)];
        if (!choices.includes(choice)) {
          choices.push(choice);
        }
      }

      return {
        matchId: match.id,
        select3: choices.includes('select3'),
        select1: choices.includes('select1'),
        select0: choices.includes('select0')
      };
    });

    setSelectedMatches(randomSelections);
    updateStats(randomSelections);

    // 自动生成组合
    setTimeout(() => {
      // 检查是否满足生成条件
      if (stats.selectedCount >= 9 && stats.selectedCount <= 14) {
        generateCombinations();
      }
    }, 500);
  };
  // 应用URL并刷新数据
  const applyUrl = () => {
    fetchMatches();
  };

  // 切换选择状态
  const toggleSelection = (matchId, type) => {
    const updated = selectedMatches.map(sm => {
      if (sm.matchId === matchId) {
        return {
          ...sm,
          [type]: !sm[type]
        };
      }
      return sm;
    });
    
    setSelectedMatches(updated);
    updateStats(updated);
  };

  // 更新统计信息
  const updateStats = (selections) => {
    const validSelections = selections.filter(sm => sm.select3 || sm.select1 || sm.select0);
    const selectedCount = validSelections.length;
    
    // 计算组合数 C(n,9)
    let comboCount = 0;
    if (selectedCount >= 9 && selectedCount <= 14) {
      comboCount = combination(selectedCount, 9);
    }
    
    // 估算总注数
    let totalBets = 0;
    if (comboCount > 0) {
      let totalChoices = 0;
      validSelections.forEach(sm => {
        let cnt = 0;
        if (sm.select3) cnt++;
        if (sm.select1) cnt++;
        if (sm.select0) cnt++;
        totalChoices += cnt;
      });
      
      const avgChoices = totalChoices / selectedCount;
      totalBets = Math.round(comboCount * Math.pow(avgChoices, 9));
    }
    
    setStats({ selectedCount, comboCount, totalBets });
  };

  // 计算组合数 C(n,k)
  const combination = (n, k) => {
    if (k > n) return 0;
    if (k === 0 || k === n) return 1;
    k = Math.min(k, n - k);
    
    let result = 1;
    for (let i = 1; i <= k; i++) {
      result = result * (n - k + i) / i;
    }
    return Math.round(result);
  };

  // 生成组合
  const generateCombinations = async () => {
    if (stats.selectedCount < 9 || stats.selectedCount > 14) {
      alert(`请选择9-14场比赛！当前已选择${stats.selectedCount}场`);
      return;
    }
    
    try {
      setLoading(true);
      const validSelections = selectedMatches.filter(sm => sm.select3 || sm.select1 || sm.select0);
      
      const response = await axios.post('/api/lottery/generate', {
        selectedMatches: validSelections
      });
      
      setCombinations(response.data.combinations);
      setResultStats({
        totalCombinations: response.data.totalCombinations,
        totalBets: response.data.totalBets,
        totalAmount: response.data.totalAmount
      });
    } catch (error) {
      console.error('生成组合失败:', error);
      alert('生成组合失败，请重试');
    } finally {
      setLoading(false);
    }
  };



// 生成单场比赛的完整信息（包含赔率）
  const getMatchDetails = (matchId) => {
    const match = matches.find(m => m.id === matchId);
    if (!match) return '';
    return `${match.home} vs ${match.away} (${match.odds3}/${match.odds1}/${match.odds0})`;
  };

  const fallbackExportAsImage = async (comboIndex = null) => {
    const tempContainer = document.createElement('div');
    tempContainer.style.width = '800px';
    tempContainer.style.backgroundColor = 'white';
    tempContainer.style.padding = '20px';
    tempContainer.style.position = 'absolute';
    tempContainer.style.top = '-9999px';
    tempContainer.style.visibility = 'hidden';
    document.body.appendChild(tempContainer);

    // 标题
    const title = document.createElement('h2');
    title.style.textAlign = 'center';
    title.style.margin = '10px 0 20px';
    title.style.fontFamily = 'SimHei, sans-serif';
    title.style.color = '#333333';
    title.style.fontSize = '18px';
    title.textContent = `胜负彩任9组合 - ${new Date().toLocaleDateString().replace(/\//g, '')}`;
    tempContainer.appendChild(title);

    // 统计信息
    const stats = document.createElement('div');
    stats.style.marginBottom = '15px';
    stats.style.fontFamily = 'SimHei, sans-serif';
    stats.style.fontSize = '14px';
    stats.style.color = '#666666';
    stats.textContent = `总组合数: ${resultStats.totalCombinations} | 总注数: ${resultStats.totalBets} | 总金额: ${resultStats.totalAmount}元`;
    tempContainer.appendChild(stats);

    const targetCombinations = comboIndex !== null
        ? [combinations[comboIndex]]
        : combinations;

    // 组合内容
    targetCombinations.forEach((combo, index) => {
      const displayIndex = comboIndex !== null ? comboIndex + 1 : index + 1;
      const comboDiv = document.createElement('div');
      comboDiv.style.border = '1px solid #e0e0e0';  // 组合外框使用#e0e0e0
      comboDiv.style.padding = '15px';
      comboDiv.style.marginBottom = '15px';
      comboDiv.style.borderRadius = '6px';
      comboDiv.style.boxShadow = '0 2px 5px rgba(0,0,0,0.05)';  // 增加轻微阴影

      // 组合编号
      const comboHeader = document.createElement('div');
      comboHeader.style.fontWeight = 'bold';
      comboHeader.style.marginBottom = '15px';
      comboHeader.style.color = '#1296db';
      comboHeader.style.fontSize = '16px';
      comboHeader.textContent = `组合 ${displayIndex}`;
      comboDiv.appendChild(comboHeader);

      // 表头
      const headerDiv = document.createElement('div');
      headerDiv.style.display = 'flex';
      headerDiv.style.fontWeight = 'bold';
      headerDiv.style.marginBottom = '10px';
      headerDiv.style.color = '#333';
      headerDiv.innerHTML = `
      <div style="width: 5%; text-align: center; border: 1px solid #e0e0e0; padding: 5px; background-color: #f5f5f5;">序号</div>
      <div style="width: 20%; border: 1px solid #e0e0e0; padding: 5px; background-color: #f5f5f5;">联赛</div>
      <div style="width: 25%; text-align: center; border: 1px solid #e0e0e0; padding: 5px; background-color: #f5f5f5; border-right: 1px solid white;">胜（主队）</div>
      <div style="width: 15%; text-align: center; border: 1px solid #e0e0e0; padding: 5px; background-color: #f5f5f5; border-left: none; border-right: 1px solid white;">平</div>
      <div style="width: 35%; text-align: center; border: 1px solid #e0e0e0; padding: 5px; background-color: #f5f5f5; border-left: none;">负（客队）</div>
    `;
      comboDiv.appendChild(headerDiv);

      // 比赛内容
      combo.forEach((match, matchIndex) => {
        const matchDiv = document.createElement('div');
        matchDiv.style.display = 'flex';
        matchDiv.style.height = '40px';
        matchDiv.style.marginBottom = '5px';

        // 序号
        const indexSpan = document.createElement('div');
        indexSpan.style.width = '5%';
        indexSpan.style.textAlign = 'center';
        indexSpan.style.display = 'flex';
        indexSpan.style.alignItems = 'center';
        indexSpan.style.justifyContent = 'center';
        indexSpan.style.border = '1px solid #e0e0e0';
        indexSpan.style.borderTop = 'none';
        indexSpan.textContent = matchIndex + 1;
        matchDiv.appendChild(indexSpan);

        // 联赛
        const leagueSpan = document.createElement('div');
        leagueSpan.style.width = '20%';
        leagueSpan.style.padding = '0 5px';
        leagueSpan.style.display = 'flex';
        leagueSpan.style.alignItems = 'center';
        leagueSpan.style.border = '1px solid #e0e0e0';
        leagueSpan.style.borderLeft = 'none';
        leagueSpan.style.borderTop = 'none';
        leagueSpan.textContent = match.league;
        matchDiv.appendChild(leagueSpan);

        // 胜选项
        const winSpan = document.createElement('div');
        winSpan.style.width = '25%';
        winSpan.style.textAlign = 'center';
        winSpan.style.display = 'flex';
        winSpan.style.alignItems = 'center';
        winSpan.style.justifyContent = 'center';
        winSpan.style.backgroundColor = match.selections.includes('3') ? '#27ae60' : 'white';
        winSpan.style.color = match.selections.includes('3') ? 'white' : '#333';
        winSpan.style.border = '1px solid #e0e0e0';
        winSpan.style.borderLeft = 'none';
        winSpan.style.borderTop = 'none';
        winSpan.style.borderRight = '1px solid white'; // 白色分割线
        winSpan.style.boxSizing = 'border-box';
        winSpan.textContent = `${match.odds3} ${match.home}`;
        matchDiv.appendChild(winSpan);

        // 平选项
        const drawSpan = document.createElement('div');
        drawSpan.style.width = '15%';
        drawSpan.style.textAlign = 'center';
        drawSpan.style.display = 'flex';
        drawSpan.style.alignItems = 'center';
        drawSpan.style.justifyContent = 'center';
        drawSpan.style.backgroundColor = match.selections.includes('1') ? '#f39c12' : 'white';
        drawSpan.style.color = match.selections.includes('1') ? 'white' : '#333';
        drawSpan.style.border = '1px solid #e0e0e0';
        drawSpan.style.borderLeft = 'none';
        drawSpan.style.borderTop = 'none';
        drawSpan.style.borderRight = '1px solid white'; // 白色分割线
        drawSpan.style.boxSizing = 'border-box';
        drawSpan.textContent = `${match.odds1}`;
        matchDiv.appendChild(drawSpan);

        // 负选项
        const loseSpan = document.createElement('div');
        loseSpan.style.width = '35%';
        loseSpan.style.textAlign = 'center';
        loseSpan.style.display = 'flex';
        loseSpan.style.alignItems = 'center';
        loseSpan.style.justifyContent = 'center';
        loseSpan.style.backgroundColor = match.selections.includes('0') ? '#e74c3c' : 'white';
        loseSpan.style.color = match.selections.includes('0') ? 'white' : '#333';
        loseSpan.style.border = '1px solid #e0e0e0';
        loseSpan.style.borderLeft = 'none';
        loseSpan.style.borderTop = 'none';
        loseSpan.style.boxSizing = 'border-box';
        loseSpan.textContent = `${match.odds0} ${match.away}`;
        matchDiv.appendChild(loseSpan);

        comboDiv.appendChild(matchDiv);
      });

      tempContainer.appendChild(comboDiv);
    });

    // 生成图片
    const contentHeight = tempContainer.offsetHeight;
    tempContainer.style.height = `${contentHeight}px`;
    tempContainer.style.visibility = 'visible';

    const canvas = await html2canvas(tempContainer, {
      scale: 2,
      useCORS: true,
      logging: false
    });

    if (comboIndex !== null) {
      return new Promise((resolve) => {
        canvas.toBlob(blob => {
          document.body.removeChild(tempContainer);
          resolve(blob);
        });
      });
    } else {
      canvas.toBlob(blob => {
        saveAs(blob, `lottery-combinations-${new Date().getTime()}.png`);
        document.body.removeChild(tempContainer);
      });
    }
  };

  // 修改exportAsZip方法确保传递完整数据
  const exportAsZip = async () => {
    if (combinations.length === 0) {
      alert('请先生成组合');
      return;
    }

    setLoading(true);
    try {
      // 准备完整的导出数据，增加联赛信息
      const exportData = {
        combinations: combinations.map(combo => combo.map(match => ({
          ...match,
          matchDetails: getMatchDetails(match.matchId),
          // 确保包含队伍信息和联赛信息
          home: matches.find(m => m.id === match.matchId)?.home || '',
          away: matches.find(m => m.id === match.matchId)?.away || '',
          league: matches.find(m => m.id === match.matchId)?.league || ''
        }))),
        totalCombinations: resultStats.totalCombinations,
        totalBets: resultStats.totalBets,
        totalAmount: resultStats.totalAmount
      };

      // 调用后端新接口生成压缩包
      const response = await axios.post('/api/lottery/generate/images/zip',
          exportData,
          { responseType: 'blob' }
      );

      // 下载zip文件
      saveAs(response.data, `lottery-combinations-${new Date().getTime()}.zip`);
    } catch (error) {
      console.error('导出ZIP失败:', error);
      alert('导出组合压缩包失败，请重试');
    } finally {
      setLoading(false);
    }
  };

// 修改exportAsImage方法，增加完整信息
  const exportAsImage = async () => {
    if (combinations.length === 0) {
      alert('请先生成组合');
      return;
    }

    try {
      setLoading(true);

      // 准备要发送到后端的数据（包含完整比赛信息）
      const exportData = {
        combinations: combinations.map(combo => combo.map(match => ({
          ...match,
          matchDetails: getMatchDetails(match.matchId)
        }))),
        totalCombinations: resultStats.totalCombinations,
        totalBets: resultStats.totalBets,
        totalAmount: resultStats.totalAmount,
        matches: matches // 发送完整比赛数据供后端使用
      };

      // 调用后端接口生成图片
      const response = await axios.post('/api/lottery/generate/image',
          exportData,
          { responseType: 'blob' }
      );

      // 创建下载链接
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `lottery-combinations-${new Date().getTime()}.png`);
      document.body.appendChild(link);
      link.click();

      // 清理
      link.remove();
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error('导出图片失败:', error);
      // 失败时使用前端降级方案
      alert('服务器生成图片失败，将使用备用方案生成');
      fallbackExportAsImage();
    } finally {
      setLoading(false);
    }
  };

  // 清空选择
  const clearAll = () => {
    const cleared = selectedMatches.map(sm => ({
      ...sm,
      select3: false,
      select1: false,
      select0: false
    }));
    
    setSelectedMatches(cleared);
    setCombinations([]);
    updateStats(cleared);
  };

  return (
      <div className="app-container">
        <header className="app-header">
          <h1>胜负彩任9组合生成器</h1>
          <div className="tab-navigation">
            <button
                className={`tab-button ${activeTab === 'main' ? 'active' : ''}`}
                onClick={() => setActiveTab('main')}
            >
              主功能区
            </button>
            <button
                className={`tab-button ${activeTab === 'matchList' ? 'active' : ''}`}
                onClick={() => setActiveTab('matchList')}
            >
              比赛列表导出
            </button>
          </div>
        </header>
        {activeTab === 'main' && (
            // 这里放原有的主功能区内容
            <>
        {/* 期号输入区域 */}
        <div className="url-input-group">
          <label>期号设置:</label>
          <div style={{display: 'flex', alignItems: 'center', gap: '10px', flexGrow: 1}}>
            <input
                type="checkbox"
                checked={useManualDrawNum}
                onChange={(e) => setUseManualDrawNum(e.target.checked)}
                id="manualDrawNum"
            />
            <label htmlFor="manualDrawNum">手动输入期号</label>

            {useManualDrawNum ? (
                <input
                    type="text"
                    value={drawNum}
                    onChange={(e) => setDrawNum(e.target.value)}
                    placeholder="请输入期号"
                    className="url-input"
                />
            ) : (
                <select
                    value={selectedDrawNum}
                    onChange={(e) => setSelectedDrawNum(e.target.value)}
                    className="draw-num-select"
                >
                  <option value="">请选择期号</option>
                  {drawNums.map(num => (
                      <option key={num} value={num}>{num}</option>
                  ))}
                </select>
            )}

            <button onClick={applyUrl} className="apply-url-btn">加载数据</button>
          </div>
        </div>

        {/* 随机选择按钮组 */}
        <div className="button-group">
          <button onClick={() => randomSelectAndGenerate(9)} className="btn random-btn">
            随机9场
          </button>
          <button onClick={() => randomSelectAndGenerate(10)} className="btn random-btn">
            随机10场
          </button>
          <button onClick={() => randomSelectAndGenerate(11)} className="btn random-btn">
            随机11场
          </button>
          <button onClick={() => randomSelectAndGenerate(12)} className="btn random-btn">
            随机12场
          </button>
          <button onClick={() => randomSelectAndGenerate(13)} className="btn random-btn">
            随机13场
          </button>
          <button onClick={() => randomSelectAndGenerate(14)} className="btn random-btn">
            随机14场
          </button>
        </div>
        <div className="top-bar">
          <div className="url-input-group">
            <label htmlFor="dataUrl">数据链接:</label>
            <input
                id="dataUrl"
                type="text"
                value={dataUrl}
                onChange={(e) => setDataUrl(e.target.value)}
                className="url-input"
            />
            <button onClick={applyUrl} className="btn apply-btn">应用链接</button>
          </div>

          <div className="info-bar">
            <div className="issue-info">
              第{new Date().toLocaleDateString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit'
            }).replace(/\//g, '')}期 胜负彩 任9
            </div>
            <div className="selection-stats">
              已选择场次: {stats.selectedCount} | 可生成组合数: {stats.comboCount} | 预计总注数: {stats.totalBets}
            </div>
          </div>

          <div className="button-group">
            <button onClick={fetchMatches} className="btn refresh-btn">刷新数据</button>
            <button onClick={generateCombinations} className="btn generate-btn">生成9场组合</button>
            <button onClick={exportAsImage} className="btn export-img-btn">导出组合图片</button>
            <button onClick={exportAsZip} className="btn export-zip-btn">导出多图压缩包</button>
            <button onClick={clearAll} className="btn clear-btn">清空选择</button>
          </div>
        </div>

        <div className="content-container">
          <div className="matches-container">
            <h2>比赛列表</h2>
            {loading ? (
                <div className="loading">加载中...</div>
            ) : (
                <div className="matches-table">
                  <div className="table-header">
                    <div className="table-cell">序号</div>
                    <div className="table-cell">联赛</div>
                    <div className="table-cell">时间</div>
                    <div className="table-cell">对阵</div>
                    <div className="table-cell">胜平负</div>
                  </div>

                  {matches.map((match, index) => {
                    const sm = selectedMatches.find(s => s.matchId === match.id) || {
                      select3: false,
                      select1: false,
                      select0: false
                    };
                    return (
                        <div key={match.id} className="match-row">
                          <div className="table-cell">{index + 1}</div>
                          <div className="table-cell">{match.league}</div>
                          <div className="table-cell">{match.time}</div>
                          <div className="table-cell">{match.home} vs {match.away}</div>
                          {/* 胜平负三格子组合 */}
                          <div className="table-cell">
                            <div className="selection-group">
                              <div
                                  className={`selection-cell win ${sm.select3 ? 'selected' : ''}`}
                                  onClick={() => toggleSelection(match.id, 'select3')}
                              >
                                胜 {match.odds3}
                              </div>
                              <div
                                  className={`selection-cell draw ${sm.select1 ? 'selected' : ''}`}
                                  onClick={() => toggleSelection(match.id, 'select1')}
                              >
                                平 {match.odds1}
                              </div>
                              <div
                                  className={`selection-cell lose ${sm.select0 ? 'selected' : ''}`}
                                  onClick={() => toggleSelection(match.id, 'select0')}
                              >
                                负 {match.odds0}
                              </div>
                            </div>
                          </div>
                        </div>
                    );
                  })}
                </div>
            )}
          </div>

          <div className="combinations-container">
            <h2>组合结果</h2>
            <div className="result-stats">
              总组合数: {resultStats.totalCombinations} | 总注数: {resultStats.totalBets} |
              总金额: {resultStats.totalAmount}元
            </div>

            <div id="combinations-container" className="combinations-content">
              {combinations.length === 0 ? (
                  <div className="no-combinations">请选择比赛并生成组合</div>
              ) : (
                  combinations.map((combo, index) => (
                      <div key={index} className="combination-item">
                        <div className="combo-header">组合 {index + 1}</div>
                        <div className="combo-matches">
                          {combo.map(match => (
                              <div key={match.matchId} className="combo-match">
                                <span className="match-id">{match.matchId}.</span>
                                <span className="match-teams">{match.home} vs {match.away}</span>
                                <span className="match-selections">
                          {match.selections.join(', ')}
                        </span>
                              </div>
                          ))}
                        </div>
                      </div>
                  ))
              )}
            </div>
          </div>
        </div>
        </>
        )}

        {activeTab === 'matchList' && (
            <MatchListTab />
        )}
      </div>
  );
}

export default App;